package com.spice.service.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spice.common.constant.PermissionConstant;
import com.spice.common.exception.SpiceException;
import com.spice.common.result.Response;
import com.spice.common.result.ResultCodeEnum;
import com.spice.common.util.CheckUtil;
import com.spice.service.util.ShiroUtil;
import com.spice.service.entity.form.EditEntityForm;
import com.spice.service.entity.form.PageForm;
import com.spice.service.entity.pojo.User;
import com.spice.service.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    UserService userService;

    @ApiOperation("获取所有用户信息")
    @PostMapping(value = "/getAllUsers", produces = "application/json;charset=UTF-8")
    public Response getAllUsers() {
        // 确认是否登录
        if (!ShiroUtil.isAuthenticated()) {
            throw new SpiceException(ResultCodeEnum.NO_AUTHENTICATION);
        }

        List<User> users = userService.getBaseMapper().selectList(null);
        users.forEach(User::desensitization);

        return Response.ok().data("records", users);
    }

    @ApiOperation("按页获取用户信息")
    @PostMapping(value = "/getUsersByPage", produces = "application/json;charset=UTF-8")
    public Response test(@RequestBody PageForm<User> pageForm) {
        // 确认是否登录
        if (!ShiroUtil.isAuthenticated()) {
            throw new SpiceException(ResultCodeEnum.NO_AUTHENTICATION);
        }
        // 检测必要参数是否缺失
        if (CheckUtil.objectsHasNull(pageForm,
                pageForm.getCurrentPage(),
                pageForm.getSize())) {
            return Response.setResult(ResultCodeEnum.PARAM_LACK);
        }

        // 生成page
        Page<User> page = userService.page(
                new Page<>(pageForm.getCurrentPage(), pageForm.getSize()),
                pageForm.getQueryWrapper());
        page.getRecords().forEach(User::desensitization);

        return Response.ok()
                .data("records", page.getRecords())
                .data("currentPage", page.getCurrent())
                .data("size", page.getSize())
                .data("totalPage", (page.getTotal() + page.getSize() - 1) / page.getSize())
                .data("hasNext", page.hasNext())
                .data("hasPrevious", page.hasPrevious());
    }

    @ApiOperation("编辑用户信息(save,remove,update)")
    @PostMapping(value = "/editUser/{method}", produces = "application/json;charset=UTF-8")
    public Response getAllUsers(@PathVariable("method") String method,
                                @RequestBody EditEntityForm<User> editEntityForm) {

        // 判断是否登录
        if (!ShiroUtil.isAuthenticated()) {
            return Response.setResult(ResultCodeEnum.NO_AUTHENTICATION);
        }
        // 判断是否有权限
        if (!ShiroUtil.hasRoles(PermissionConstant.ROOT_ROLE)) {
            return Response.setResult(ResultCodeEnum.NO_PERMISSION);
        }
        // 判断是否有method参数
        if (CheckUtil.objectsHasNull(method)) {
            return Response.setResult(ResultCodeEnum.PARAM_LACK);
        }

        // 初始化参数
        User newUser = editEntityForm.getT().cleanup();
        Long id = editEntityForm.getId();
        if ("save".equals(method)) {
            // 添加用户（注册）
            return userService.saveUser(newUser);
        } else if ("remove".equals(method)) {
            // 删除用户
            return userService.removeUser(id);
        } else if ("update".equals(method)) {
            // 更新用户
            return userService.updateUser(id, newUser);
        }
        return Response.ok().message("未执行任何操作");
    }
}
